/*
 * serial.h
 *
 *  Created on: 2017年3月28日
 *      Author: chenshisheng
 */

#ifndef SERIAL_H_
#define SERIAL_H_

#include "main.h"
#include "ringbuffer.h"

#include "message_queue.h"

#define SERIAL_HAVE_UART0  1
#define SERIAL_HAVE_UART1  0
#define SERIAL_HAVE_UART2  1
#define SERIAL_HAVE_UART3  0
#define SERIAL_HAVE_UART4  0
#define SERIAL_HAVE_UART5  0
#define SERIAL_HAVE_UART6  0
#define SERIAL_HAVE_LPUART1 0

#define SERIAL_FLAG_AUTO_LINE 0x00100

// 收发缓存大小
#define SERIAL_RX_BUFFER_SIZE 64
#define SERIAL_TX_BUFFER_SIZE 64

// 串口序号
typedef enum
{
#if SERIAL_HAVE_UART0
    Serial_0,
#endif

#if SERIAL_HAVE_UART1
    Serial_1,
#endif

#if SERIAL_HAVE_UART2
    Serial_2,
#endif

#if SERIAL_HAVE_UART3
    Serial_3,
#endif

#if SERIAL_HAVE_UART4
    Serial_4,
#endif

#if SERIAL_HAVE_UART5
    Serial_5,
#endif

#if SERIAL_HAVE_UART6
    Serial_6,
#endif

#if SERIAL_HAVE_LPUART1
    Serial_LP1,
#endif

    Serial_Max
}Serial_t;

typedef enum
{
//    Serial_Direction_None = LL_USART_DIRECTION_NONE,
    Serial_Direction_Rx   = 0,
    Serial_Direction_Tx   = 1,
    Serial_Direction_TxRx = 2
}Serial_Direction_t;

typedef enum
{
    Serial_Ctl_Enable,
    Serial_Ctl_Disable,
    Serial_Ctl_GetName,
    Serial_Ctl_SetFlags,
    Serial_Ctl_ClearFlags,
    Serial_Ctl_ClearTxBuffer,
    Serial_Ctl_ClearRxBuffer,
//    Serial_Ctl_GetBuadRate,
//    Serial_Ctl_RxCmd,
    Serial_Ctl_IsTxDone,
    Serial_Ctl_DeleteLastRxBufferByte,
//    Serial_Ctl_GetUart,
    Serial_Ctl_SetDirection,
}Serial_Ctl_t;

typedef void (* Serial_Callback_t)(Serial_t serial);
typedef bool (* Serial_RxByteCallback_t)(Serial_t serial, uint8_t b);

void Serial_Init(void);
void Serial_DeInit(void);
void Serial_IRQHandler(Serial_t serial);
void Serial_SetCallbacks(
        Serial_t serial,
        Serial_Callback_t onTxBegin,
        Serial_Callback_t onTxComplete,
        Serial_RxByteCallback_t onRxByte);
void Serial_GetCallbacks(
        Serial_t serial,
        Serial_Callback_t *onTxBegin,
        Serial_Callback_t *onTxComplete,
        Serial_RxByteCallback_t *onRxByte);
void Serial_SendByte(Serial_t serial, uint8_t b);
void Serial_SendByteWithoutBuffer(Serial_t serial, uint8_t b);
void Serial_Send(Serial_t serial, const void *data, unsigned int size);
void Serial_SendString(Serial_t serial, const char *str);
int Serial_RecvByte(Serial_t serial, uint8_t *byteOut, unsigned int timeoutMs);
unsigned int Serial_Recv(Serial_t serial, void *data, unsigned int size, unsigned int timeoutMs);
int Serial_RecvByteWithoutBuffer(Serial_t serial, uint8_t *byteOut);
int Serial_RecvLine(Serial_t serial, char buf[], unsigned int size, char end);
int Serial_IoCtl(int serial, int ctl, ...);

void Serial_TestCmd(Serial_t serial, bool isEnable);
void Serial_OnTest(MsgQueue_Msg_t *msg);

#endif /* SERIAL_H_ */
